#ifndef SERIALPORT_H
#define SERIALPORT_H

#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QVariant>
#include <QTimer>
#include "baseport.h"
#include "portstatistics.h"

struct SerialPortSetting
{
    QString 					name = "COM2";

    bool						isAutoOpen = false;
    qint32						baudRate = 115200;
    QSerialPort::StopBits 		stopBits = QSerialPort::OneStop;
    QSerialPort::DataBits		dataBits = QSerialPort::Data8;
    QSerialPort::Parity			parity = QSerialPort::NoParity;
    QSerialPort::FlowControl	flowContrl = QSerialPort::NoFlowControl;

    QSerialPort::OpenMode		openMode = QSerialPort::ReadWrite;
};
Q_DECLARE_METATYPE(SerialPortSetting)

class SerialPort : public BasePort
{
    Q_OBJECT
public:
    explicit SerialPort(QObject *parent = nullptr);
    virtual ~SerialPort() override;

    virtual PortType getPortType() override;

    virtual void setConfig(QVariant &config) override;
    virtual QVariant getConfig(void) override;
    virtual bool open(void) override;
    virtual bool isOpen(void) override;
    virtual bool close(void) override;
    virtual qint32 write(const QByteArray &ba) override;
    virtual qint32 read(QByteArray &ba) override;

    QString errorString() const;
    void clearError();

    // 跨线程调用
    bool openSync(int timeout_ms = -1);
    bool closeSync(int timeout_ms = -1);
    qint32 writeSync(const QByteArray &ba, int timeout_ms = -1);
    qint32 readSync(QByteArray &ba, int timeout_ms = -1);

    static QSerialPort::StopBits toStopBit(const QString &bit);
    static QSerialPort::DataBits toDataBit(const QString &bit);
    static QSerialPort::Parity toParityBit(const QString &bit);
    static QSerialPort::FlowControl toFlowControl(const QString &bit);

    static QString fromStopBit(QSerialPort::StopBits bit);
    static QString fromDataBit(QSerialPort::DataBits bit);
    static QString fromParityBit(QSerialPort::Parity bit);
    static QString fromFlowControl(QSerialPort::FlowControl bit);

public slots:
    void onError(QSerialPort::SerialPortError error);
    void onRead(void);

private:
    QSerialPort 		    *m_port = nullptr;
    SerialPortSetting	    m_setting;
};

#endif // SERIALPORT_H
